﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ERF.Menu
{
    /// <summary>
    /// This class creates a menu. The only thing this class does
    /// over a MenuList is to maintain the current index
    /// of the selected menu item. It also has methods for
    /// changing the index.
    /// </summary>

    public class Menu : MenuList
    {
        private MenuList currentList;
        private int selectedIndex = 0;

        public Menu(String title) : base(title)
        {
            currentList = this;
            this.action = SubmitMenu;
        }
        /// <summary>
        /// Selects a Menu in the tree of items.
        /// </summary>
        public MenuList CurrentList
        {
            get { return currentList; }
            set {
                currentList = value;
                selectedIndex = currentList.MenuItems.IndexOf(currentList.SelectedItem, 0, currentList.MenuItems.Count);
            }
        }

        /// <summary>
        /// Sets or gets the index of the current selected menu item.
        /// </summary>
        public int SelectedIndex
        {
            get { return selectedIndex; }
            set {
                if (selectedIndex >= 0 && selectedIndex < MenuItems.Count)
                {
                    selectedIndex = value;
                    currentList.SelectedItem = MenuItems[SelectedIndex];
                }
            }
        }

        /// <summary>
        /// Goes back to the parent menu list if it exists.
        /// </summary>
        public void Back()
        {
            if (currentList.ParentList != null)
                CurrentList = currentList.ParentList;
        }

        /// <summary>
        /// Selects the previous menu item in the current menu list.
        /// </summary>
        public void SelectPrevious()
        {
            selectedIndex--;

            if (selectedIndex < 0)
                selectedIndex = currentList.MenuItems.Count - 1;

            currentList.SelectedItem = currentList.MenuItems[selectedIndex];
        }
        /// <summary>
        /// Selects the next item in the current menu list.
        /// </summary>
        public void SelectNext()
        {
            selectedIndex++;

            if (selectedIndex > currentList.MenuItems.Count - 1)
                selectedIndex = 0;

            currentList.SelectedItem = currentList.MenuItems[selectedIndex];
        }

        /// <summary>
        /// Submits the current list that is selected.
        /// </summary>
        private void SubmitMenu()
        {
            currentList.SelectedItem.Submit();
        }
    }
}
